package com.taptech.doufu.ui.fragment.weex;

import android.content.Context;

import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.taobao.weex.IWXRenderListener;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.common.WXRenderStrategy;
import com.taobao.weex.utils.WXResourceUtils;
import com.taptech.doufu.weex.TFWXUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/18/018.
 */

public class TFWXView extends LinearLayout implements IWXRenderListener {
    WXSDKInstance mWXSDKInstance;

    ArrayList<WXSDKInstance> presentWXSDKInstances;


    protected HashMap param;

    public TFWXView(Context context) {
        super(context);
    }

    public TFWXView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TFWXView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void initView(Context context,HashMap param) {
        this.param = param;
        mWXSDKInstance = new WXSDKInstance(context);
        mWXSDKInstance.registerRenderListener(this);
        /**
         * WXSample 可以替换成自定义的字符串，针对埋点有效。
         * template 是.we transform 后的 js文件。
         * option 可以为空，或者通过option传入 js需要的参数。例如bundle js的地址等。
         * jsonInitData 可以为空。
         * width 为-1 默认全屏，可以自己定制。
         * height =-1 默认全屏，可以自己定制。
         */
        try {
            HashMap options = getOptions();
            String url = getUrl();
            if (url.startsWith("http") == true){
                mWXSDKInstance.renderByUrl("TF",url, options , null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
            }else {
                mWXSDKInstance.render("TF",url, options , null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        setBackgroundColor(WXResourceUtils.getColor("bg|bg"));
    }


    /**
     * 获取传值额外参数 {data：map} 和bundleUrl同级
     */
    private HashMap getOptions(){
        Object param = this.param;
        HashMap<String,Object> options = new HashMap<>();
        String url = (String) ((Map) param).get("url");
        options.put("bundleUrl",url);
        if (param instanceof Map){
            param = ((Map) param).get("data");
            if (param instanceof Object){

                if (param instanceof HashMap){
                    options.put("data",param);
                }else {
                    options.put("data", JSON.parseObject(param.toString()));
                }
            }
        }
        return options;
    }
    /**
     * 获取Url
     */
    private String getUrl(){
        Object param = this.param;
        if (param instanceof Map){
            String url = (String) ((Map) param).get("url");
            return TFWXUtil.handleWXUrl(url);
        }
        return "";
    }

    @Override
    public void onViewCreated(WXSDKInstance instance, View view) {
        addView(view);
        final WeakReference<TFWXView> weakSelf = new WeakReference<>(this);
        if (view instanceof ViewGroup){
            ((ViewGroup)view).setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
                @Override
                public void onChildViewAdded(View parent, View child) {
                    TFWXView self = weakSelf.get();
                    if (self != null){
                        if (self.presentWXSDKInstances != null){
                            if (self.presentWXSDKInstances.size() > 0){
                                WXSDKInstance inatance = self.presentWXSDKInstances.get(self.presentWXSDKInstances.size() - 1);
                                if (inatance.getContainerView() != null){
                                    inatance.getContainerView().bringToFront();
                                }

                            }
                        }
                    }
                }

                @Override
                public void onChildViewRemoved(View parent, View child) {

                }
            });

        }
    }

    @Override
    public void onRenderSuccess(WXSDKInstance instance, int width, int height) {

    }

    @Override
    public void onRefreshSuccess(WXSDKInstance instance, int width, int height) {

    }

    @Override
    public void onException(WXSDKInstance instance, String errCode, String msg) {

    }



}
